﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using XmlSockets;

namespace LibXmlSocketTestClient
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        private ClientXmlSocket _client;
       
        


        public MainWindow()
        {
            InitializeComponent();
            _client = new ClientXmlSocket();

            _client.Received += _received;
            _client.Closed += _closed;
        }

        

        private async void ConnectionButton_Click(object sender, RoutedEventArgs e)
        {
            await _client.ConnectAsync(this.IPText.Text, int.Parse(this.PortText.Text));
            _showMessage("接続開始");
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            _client.Close();
        }

        private  void MessageRequestButton_Click(object sender, RoutedEventArgs e)
        {
            _sendAsync();
        }

        private async void _sendAsync()
        {
            var requestMessage = new XElement("thread");
            requestMessage.SetAttributeValue("thread", this.ThreadText.Text);
            requestMessage.SetAttributeValue("res_from", "-200");
            requestMessage.SetAttributeValue("version", "20061206");
            requestMessage.SetAttributeValue("scores", "1");
            await _client.SendAsync(requestMessage);
        }

        private void _showMessage(string message)
        {
            this.MessageView.Text += message + "\r\n";
        }

        private void MainWindow_Closed(object sender, EventArgs e)
        {
            _client.Dispose();
        }

        private void _closed(ClientXmlSocketCloseEventArgs args)
        {
            _showMessage("切断しました");
        }

        private void _received(ClientXmlSocketReceiveEventArgs args)
        {
            string showmMessage = "";

            foreach (var message in args.Messages)
            {
                showmMessage += message.ToString() + "\r\n";
            }




            _showMessage(showmMessage);
            _showMessage("messageCount:" + args.Messages.Count() + "\r\n");
        }
    }
}
